// echo_client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PORT 7000  // 客户端使用的端口
#define BUFFER_SIZE 1024
#define PREFIX "client: "

int main() {
    int sock = 0;
    struct sockaddr_in serv_addr;
    char buffer[BUFFER_SIZE];

    // 创建套接字
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf(" Socket creation error ");
        return -1;
    }

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);

    // 转换地址
    if (inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) <= 0) {
        printf(" Invalid address/ Address not supported ");
        return -1;
    }

    // 连接到服务器
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
        printf(" Connection Failed ");
        return -1;
    }

    while (1) {
        printf("Enter message (or 'q' to quit): ");
        fgets(buffer, BUFFER_SIZE, stdin);

        // 检查是否输入 'q' 以退出
        if (strncmp(buffer, "q", 1) == 0) {
            printf("Exiting...  ");
            break;
        }

        // 添加前缀
        char message[BUFFER_SIZE];
        snprintf(message, BUFFER_SIZE, "%s%s", PREFIX, buffer);

        // 打印带有前缀的消息
        printf("Sending:\n%s", message);

        // 发送数据
        send(sock, message, strlen(message), 0);

        // 接收相同的数据
        ssize_t bytes_read = read(sock, buffer, BUFFER_SIZE);
        if (bytes_read > 0) {
            buffer[bytes_read] = '\0';  // 终止字符串
            printf("Echo from server: \n%s", buffer);
        }
    }

    // 关闭套接字
    close(sock);
    return 0;
}

